package org.x.usermod.service.impl;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.x.usermod.dto.LogDetailDTO;
import org.x.usermod.mapper.LogMapper;
import org.x.usermod.dto.LogDTO;
import org.x.usermod.dto.LogQueryParamDTO;
import org.x.usermod.entity.SysLog;
import org.x.usermod.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Objects;

@Service
public class LogServiceImpl implements LogService {

    @Autowired
    private LogMapper logMapper;

    @Override
//分页查询日志列表
    public Page<LogDTO> getLogList(LogDTO logDTO) {
        // 构建查询条件
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select("*")
                .from("sys_log");

        // 添加条件查询
        if (logDTO != null) {
            if (StringUtils.hasText(logDTO.getAction())) {
                queryWrapper.and("action like concat('%', ?, '%')", logDTO.getAction());
            }
            if (StringUtils.hasText(logDTO.getTargetType())) {
                queryWrapper.and("target_type like concat('%', ?, '%')", logDTO.getTargetType());
            }
            if (logDTO.getUserId() != null) {
                queryWrapper.and("user_id = ?", logDTO.getUserId());
            }
            if (logDTO.getTargetId() != null) {
                queryWrapper.and("target_id = ?", logDTO.getTargetId());
            }
            if (logDTO.getCreatedTime() != null) {
                queryWrapper.and("created_time >= ?", logDTO.getCreatedTime());
            }
        }

        // 添加排序条件（按创建时间倒序）
        queryWrapper.orderBy("created_time", false);

        // 执行分页查询
        //PageNum和PageSize默认值
        if (logDTO.getPageNum() == null) {
            logDTO.setPageNum(1);
        }
        if (logDTO.getPageSize() == null) {
            logDTO.setPageSize(10);
        }
        //PageNum
        Page<LogDTO> page = new Page<>(logDTO.getPageNum(), logDTO.getPageSize());
        return logMapper.paginateAs(page, queryWrapper, LogDTO.class);
    }

    @Override
    public LogDetailDTO getLogDetail(Long id) {
        SysLog sysLog = logMapper.selectOneById(id);
        if (sysLog == null) {
            return null;
        }

        LogDetailDTO dto = new LogDetailDTO();
        dto.setId(sysLog.getId());
        dto.setUserId(sysLog.getUserId());
        dto.setAction(sysLog.getAction());
        dto.setTargetType(sysLog.getTargetType());
        dto.setTargetId(sysLog.getTargetId());
        dto.setIp(sysLog.getIp());
        dto.setCreatedTime(sysLog.getCreatedTime());
        dto.setDetail(sysLog.getDetail());
        return dto;
    }

    @Override
    public void exportLog(OutputStream outputStream) throws IOException {
        List<LogDetailDTO> logs = logMapper.selectListByQueryAs(
                QueryWrapper.create()
                        .select("*")
                        .from("sys_log")
                        .orderBy("created_time", false),
                LogDetailDTO.class
        );

        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("操作日志");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"ID", "用户ID", "操作类型", "目标类型", "目标ID", "IP地址", "创建时间", "操作详情"};

            // 设置表头样式（可选）
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);

            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }

            // 填充数据
            int rowNum = 1;
            for (LogDetailDTO log : logs) {
                Row row = sheet.createRow(rowNum);
                row.createCell(0).setCellValue(log.getId());

                // 处理userId为null的情况
                if (log.getUserId() == null) {
                    row.createCell(1).setCellValue("");
                } else {
                    row.createCell(1).setCellValue(log.getUserId());
                }

                row.createCell(2).setCellValue(log.getAction());
                row.createCell(3).setCellValue(log.getTargetType());

                // 处理targetId为null的情况
                if (log.getTargetId() == null) {
                    row.createCell(4).setCellValue("");
                } else {
                    row.createCell(4).setCellValue(log.getTargetId());
                }

                row.createCell(5).setCellValue(log.getIp());

                // 格式化日期（可选）
                if (log.getCreatedTime() != null) {
                    CellStyle dateStyle = workbook.createCellStyle();
                    CreationHelper createHelper = workbook.getCreationHelper();
                    dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd hh:mm:ss"));
                    Cell dateCell = row.createCell(6);
                    dateCell.setCellValue(log.getCreatedTime());
                    dateCell.setCellStyle(dateStyle);
                } else {
                    row.createCell(6).setCellValue("");
                }

                row.createCell(7).setCellValue(log.getDetail() != null ? log.getDetail() : "");
                rowNum++;
            }

            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            workbook.write(outputStream);
        }
    }

}